﻿package {
	import flash.display.*;
	import flash.external.*;
	import flash.net.*;
	import flash.text.*;
	import flash.events.*;
	public class Listener extends LC {
		public var senders:Object = {};
		public function Listener():void {
			//收听者，固定连接到一个名字进行侦听，收听多个发送者数据
			name_conn = "_" + lc + "_" + LISTENER;
			try {
				lc_conn.connect(name_conn);
			} catch (e:ArgumentError) {
				eicall(onstate, e.message);
			}
			eicall(onloaded, name_conn);
		}
		override public function sendData(... rest):void {
			//对所有加入的发送者返回数据
			for (var ln:String in senders) {
				if (senders[ln] is LocalConnection) {
					senders[ln].send(ln, "getData", rest[0]);
				}
			}
		}
		
		public function reply(cn:String):void {
			if (!senders[cn]) {
				var newlc = new LocalConnection();
				newlc.addEventListener(StatusEvent.STATUS, onStatus);
				senders[cn] = newlc;
			}
		}
		
		override public function getData(... rest):void {
			//收到数据，顺便连接到发送者，便于返回数据
			reply(rest[0]);
			eicall(ondata, rest[1]);
		}
		
		override public function onStatus(e:StatusEvent):void {
			super.onStatus(e);
			if (e.level == "error") {
				for (var ln:String in senders) {
					if (senders[ln] == e.currentTarget) {
						senders[ln] = null;
						delete senders[ln];
					}
				}
			}
        }
		
	}
}